package com.raceway.ihcenterapp.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;

import com.raceway.ihcenterapp.domain.Audio;
import com.raceway.ihcenterapp.domain.IHS;
import com.raceway.ihcenterapp.domain.HelpRequest;
import com.raceway.ihcenterapp.domain.Person;
import com.raceway.ihcenterapp.domain.PhoneInfo;
import com.raceway.ihcenterapp.domain.Picture;
import com.raceway.ihcenterapp.domain.UserRole;
import com.raceway.ihcenterapp.domain.Video;

import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RooWebScaffold(path = "helprequests", formBackingObject = HelpRequest.class,update=false,delete=false,create=false)
@RequestMapping("/helprequests")
@Controller
public class HelpRequestController {
	UserDetails user;
	Collection<GrantedAuthority> authorities;
	Iterator<GrantedAuthority> roles;
	String role;
	UserRole  userRoles;
	Person person;
	EntityManager em;
	
	@RequestMapping(method=RequestMethod.POST,value="/newAndroidHelpRequest")
	public void newAndroidHelpRequest(HttpServletRequest httpRequest){
		String deneme;
		
	}


	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("helpRequest", HelpRequest.findHelpRequest(id));
        
        return "helprequests/update";
    }
	
    @RequestMapping(value = "/findphonehelprequests/{id}", method = RequestMethod.GET)
    public String videosOfHelpRequest(@PathVariable("id") Long id, Model model) {

        PhoneInfo phoneInfo=PhoneInfo.findPhoneInfo(id);
            model.addAttribute("helprequests",HelpRequest.findHelpRequestsByPhoneInfo(phoneInfo).getResultList() );
        return "helprequests/list";
    }
    
    @RequestMapping(value = "/findAssignedRequests/{id}", method = RequestMethod.GET)
    public String helpRequestsOfASI(@PathVariable("id") Long id, Model model) {

        IHS asi=IHS.findIHS(id);
        EntityManager em = HelpRequest.entityManager();
        TypedQuery<HelpRequest> q = em.createQuery("SELECT HelpRequest FROM HelpRequest AS helprequest WHERE helprequest.assignedASI1 = :asi", HelpRequest.class);
        q.setParameter("asi", asi);      
            model.addAttribute("helprequests",q.getResultList());
        return "helprequests/list";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model model) {
        addDateTimeFormatPatterns(model);
        HelpRequest helpRequest=HelpRequest.findHelpRequest(id);
        model.addAttribute("helprequest", HelpRequest.findHelpRequest(id));
        model.addAttribute("itemId", id);
        List<Video> videos=new ArrayList<Video>();
        videos= Video.findVideosByHelpRequestId(helpRequest).getResultList();
        model.addAttribute("videoCount", videos.size());
        model.addAttribute("audioCount",Audio.findAudiosByHelpRequestId(helpRequest).getResultList().size());
        model.addAttribute("pictureCount",Picture.findPicturesByHelpRequestId(helpRequest).getResultList().size());
        return "helprequests/show";
    }

	@RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model model) {
		user=(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		authorities=user.getAuthorities();
		roles=authorities.iterator();
		role=roles.next().toString();
		if(role.equalsIgnoreCase(userRoles.ROLE_IHS_USER.toString())){
			Query query = Person.findPeopleByUserName(user.getUsername());
			person = (Person) query.getSingleResult();
			IHS ihs=person.getWorkedIHS();
			
			 model.addAttribute("helprequests", HelpRequest.findHelpRequestsByAssignedASI1(ihs).getResultList());
			
		}else{
			

		if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            model.addAttribute("helprequests", HelpRequest.findHelpRequestEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) HelpRequest.countHelpRequests() / sizeNo;
            model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
    			 model.addAttribute("helprequests", HelpRequest.findAllHelpRequests());

        }
		}
        addDateTimeFormatPatterns(model);
        return "helprequests/list";
    }

	@RequestMapping(params = { "find=ByRequestUri", "form" }, method = RequestMethod.GET)
    public String findHelpRequestsByRequestUriForm(Model model) {
        return "helprequests/findHelpRequestsByRequestUri";
    }

	@RequestMapping(params = "find=ByRequestUri", method = RequestMethod.GET)
    public String findHelpRequestsByRequestUri(@RequestParam("requestUri") String requestUri, Model model) {
        model.addAttribute("helprequests", HelpRequest.findHelpRequestsByRequestUri(requestUri).getResultList());
        return "helprequests/list";
    }

	@RequestMapping(params = { "find=ByPhoneId", "form" }, method = RequestMethod.GET)
    public String findHelpRequestsByPhoneIdForm(Model model) {
        return "helprequests/findHelpRequestsByPhoneId";
    }

	@RequestMapping(params = "find=ByPhoneId", method = RequestMethod.GET)
    public String findHelpRequestsByPhoneId(@RequestParam("phoneId") String phoneId, Model model) {
        model.addAttribute("helprequests", HelpRequest.findHelpRequestsByPhoneId(phoneId).getResultList());
        return "helprequests/list";
    }

	@RequestMapping(params = { "find=ByPhoneInfo", "form" }, method = RequestMethod.GET)
    public String findHelpRequestsByPhoneInfoForm(Model model) {
        model.addAttribute("phoneinfoes", PhoneInfo.findAllPhoneInfoes());
        return "helprequests/findHelpRequestsByPhoneInfo";
    }

	@RequestMapping(params = "find=ByPhoneInfo", method = RequestMethod.GET)
    public String findHelpRequestsByPhoneInfo(@RequestParam("phoneInfo") PhoneInfo phoneInfo, Model model) {
        model.addAttribute("helprequests", HelpRequest.findHelpRequestsByPhoneInfo(phoneInfo).getResultList());
        return "helprequests/list";
    }

	@ModelAttribute("ihss")
    public Collection<IHS> populateIHSS() {
        return IHS.findAllIHSS();
    }

	@ModelAttribute("phoneinfoes")
    public Collection<PhoneInfo> populatePhoneInfoes() {
        return PhoneInfo.findAllPhoneInfoes();
    }

	void addDateTimeFormatPatterns(Model model) {
        model.addAttribute("helpRequest_helprequestdate_date_format", DateTimeFormat.patternForStyle("MS", LocaleContextHolder.getLocale()));
    }

	@RequestMapping(params = { "find=ByAssignedASI1", "form" }, method = RequestMethod.GET)
    public String findHelpRequestsByAssignedASI1Form(Model model) {
        model.addAttribute("ihss", IHS.findAllIHSS());
        return "helprequests/findHelpRequestsByAssignedASI1";
    }

	@RequestMapping(params = "find=ByAssignedASI1", method = RequestMethod.GET)
    public String findHelpRequestsByAssignedASI1(@RequestParam("assignedASI1") IHS assignedASI1, Model model) {
        model.addAttribute("helprequests", HelpRequest.findHelpRequestsByAssignedASI1(assignedASI1).getResultList());
        return "helprequests/list";
    }
}
